In [1]:
import pandas as pd
import plotly.express as px

# Load and clean data
df = pd.read_csv('Life Expectancy Data.csv')
df.rename(columns=lambda x: x.strip(), inplace=True)
In [2]:
fig = px.choropleth(
    df,
    locations='Country',
    locationmode='country names',
    color='Life expectancy',
    animation_frame='Year',
    title='Global Life Expectancy Over Time',
    color_continuous_scale='Viridis',
    height=700,   # increase height
    width=1000,   # increase width
)
fig.show()
In [3]:
# Keep only valid numeric rows
df = df.dropna(subset=['Life expectancy', 'GDP'])
df['Population'] = pd.to_numeric(df['Population'], errors='coerce').fillna(df['Population'].median())

# Animated bubble chart
fig = px.scatter(
    df,
    x='GDP',
    y='Life expectancy',
    animation_frame='Year',
    animation_group='Country',
    size='Population',
    color='Status',
    hover_name='Country',
    log_x=True,
    size_max=60,
    title='Life Expectancy vs GDP per Capita (Animated by Year)',
    color_discrete_sequence=px.colors.qualitative.Bold
)

fig.update_layout(transition={'duration': 1000})
fig.show()
In [4]:
import plotly.graph_objects as go
corr_cols = ["Life expectancy", "GDP", "Schooling", "BMI", "Adult Mortality", "Alcohol"]
corr = df[corr_cols].corr()

fig5 = go.Figure(data=go.Heatmap(
    z=corr.values,
    x=corr.columns,
    y=corr.columns,
    colorscale="RdBu",
    zmin=-1,
    zmax=1,
    hoverongaps=False
))
fig5.update_layout(
    title=" Correlation Heatmap: Life Expectancy and Key Variables",
    template="plotly_dark"
)
fig5.show()
In [5]:
top_countries = (
    df.groupby("Country")["Life expectancy"].mean().nlargest(10).index.tolist()
)
line_df = df[df["Country"].isin(top_countries)]

fig6 = px.line(
    line_df,
    x="Year",
    y="Life expectancy",
    color="Country",
    title="Top 10 Countries: Life Expectancy Over Time",
    markers=True,
    template="plotly_dark"
)
fig6.show()
In [6]:
import pandas as pd
import plotly.graph_objects as go

# Load and clean data
df = pd.read_csv("Life Expectancy Data.csv")
df.columns = df.columns.str.strip()
df = df.dropna(subset=["Country", "Year", "Life expectancy"])
df["Year"] = pd.to_numeric(df["Year"], errors="coerce").astype(int)

# Sort by year
df = df.sort_values(["Country", "Year"])

# Prepare figure
fig = go.Figure()

countries = sorted(df["Country"].unique())

# Add one trace per country (initially hidden)
for country in countries:
    country_df = df[df["Country"] == country]
    fig.add_trace(
        go.Scatter(
            x=country_df["Year"],
            y=country_df["Life expectancy"],
            mode="lines+markers",
            name=country,
            visible=False  # start hidden
        )
    )

# Dropdown buttons (each country as a button)
buttons = []

for i, country in enumerate(countries):
    visible = [False] * len(countries)
    visible[i] = True
    buttons.append(
        dict(
            label=country,
            method="update",
            args=[
                {"visible": visible},
                {"title": f" Life Expectancy Over Time — {country}"}
            ],
        )
    )

# Add “All countries” option
buttons.insert(
    0,
    dict(
        label="All Countries",
        method="update",
        args=[
            {"visible": [True] * len(countries)},
            {"title": " Life Expectancy Over Time — All Countries"},
        ],
    )
)

# Update layout with dropdown
fig.update_layout(
    updatemenus=[
        dict(
            active=0,
            buttons=buttons,
            x=1.05,
            y=1,
            xanchor="left",
            yanchor="top",
            direction="down",
            showactive=True
        )
    ],
    title="Life Expectancy Over Time — All Countries",
    xaxis_title="Year",
    yaxis_title="Life Expectancy (years)",
    template="plotly_dark",
    height=600
)

fig.show()
In [ ]: